package com.bwie.handler;

import com.bwie.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2025/7/17 17:10
 */

@ControllerAdvice
@Slf4j
public class GlobalException {

    /**
     * @description 拦截通用异常
     * @params [e]
     * @return com.bwie.utils.R
     * @author 军哥
     * @date 2025/7/17 17:16
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R error(Exception e) {
        return R.ERROR(500, e.getMessage());
    }


    /**
     * @description 参数错误异常
     * @params [ex]
     * @return com.bwie.utils.R
     * @author 军哥
     * @date 2025/7/18 15:30
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody // 为了能够返回数据
    public R handleValidationExceptions(MethodArgumentNotValidException ex) {
        String message = null;

        Map<String, String> errors = new HashMap<>();
        for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
            if(message == null) {
                message = fieldError.getDefaultMessage();
            }
            else {
                message += ("，" + fieldError.getDefaultMessage());
            }
        }

        return R.ERROR(HttpStatus.BAD_REQUEST.value(), message);
    }


}
